import { Component, Prop, Vue, Watch } from 'vue-property-decorator'
import styles from './SelectTree.less'
@Component({})
export default class SelectTree extends Vue {
  @Prop({ default: '' }) private value!: string
  @Prop({ default: false }) private disabled!: boolean
  @Prop({ default: '' }) private parentId!: string
  @Prop({ default: false }) private loading!: boolean
  @Prop({ default: () => [] }) private defaultExpended!: any[]
  @Prop({
    default: () => ({
      children: 'subList',
      label: 'fullName',
      isLeaf: 'isLeaf',
      minSearchSize: 1, // 查询最小字数，默认2
      delay: 500, // 查询延迟
    }),
  })
  private defaultProps!: any

  private currentValue: string = ''
  private showTree: boolean = false
  private showPopover: boolean = false
  private timer: any = null
  private treeProps: any = null
  private hoverTips: any = false
  private selectVal: string = ''
  private parentHasChange: boolean = false

  protected render(h: any) {
    return (
      <div class={styles.selectTree}>
        <el-popover
          placement="bottom"
          width="350"
          popper-class={styles.popover}
          v-model={this.showPopover}
          trigger="manual"
          ref="elPopover"
        >
          <el-tooltip
            slot="reference"
            manual
            value={this.hoverTips}
            effect="dark"
            content="请先选择区域后再选择机构名称"
            placement="bottom"
          >
            <el-input
              ref="input"
              v-model={this.currentValue}
              id="elInput"
              placeholder="机构名称"
              disabled={this.disabled}
              onInput={this.onInput}
              readonly
              {...{
                nativeOn: {
                  click: this.getAllTree,
                  mouseenter: this.isShowTips,
                  mouseleave: () => {
                    this.hoverTips = false
                  },
                },
              }}
            />
          </el-tooltip>

          <div class={styles.content}>
            <el-input
              ref="search"
              class="search-box"
              placeholder="输入关键词搜索"
              v-model={this.selectVal}
              onInput={this.onInput}
            >
              <i
                class="el-icon-search"
                slot="suffix"
                onClick={() => this.queryHandler(true)}
              />
            </el-input>
            {this.showTree && (
              <el-tree
                v-loading={this.loading}
                default-expanded-keys={this.defaultExpended}
                node-key="uuid"
                empty-text=""
                ref="tree"
                {...{
                  props: { props: this.treeProps },
                }}
                lazy
                show-checkbox
                onNode-click={this.handleNodeClick}
                onCurrent-change={this.currentChange}
                onNode-expand={this.nodeExpand}
                load={this.loadNode}
                class={styles.tree}
                expand-on-click-node={false}
                render-content={this.renderContent}
              />
            )}
            {this.isEmpty && (
              <div class={styles.emptyContent}>
                {this.$slots.empty || (
                  <p class={styles.title}>
                    <i class="el-icon-warning" />
                    机构不存在
                  </p>
                )}
              </div>
            )}
          </div>
        </el-popover>
      </div>
    )
  }

  private mounted() {
    window.addEventListener('click', this.close)
  }

  private beforeDestroy() {
    this.selectVal = ''
    window.removeEventListener('click', this.close)
  }

  private get isEmpty() {
    // 判断为空
    return (
      !this.loading &&
      this.$refs['tree'] &&
      ((this.$refs['tree'] as any).treeItemArray || []).length === 0
    )
  }

  // 非建议保留功能
  private setValue(val: string) {
    this.currentValue = val
  }

  private isShowTips() {
    this.hoverTips = this.parentId.length === 0 && !this.disabled
  }

  private onInput(val: string) {
    this.$emit('input', val)

    if (this.timer) clearTimeout(this.timer)

    this.timer = setTimeout(this.queryHandler, this.defaultProps.delay)
  }

  private getAllTree(e: Event) {
    e.stopPropagation()

    if (!(this.parentId || '').trim()) {
      // this.$message.warning("请选择区域");
      this.$emit('error', {
        code: 4001,
        msg: '请选择区域',
      })

      return
    }

    this.showTree = true
    this.showPopover = true

    this.$nextTick(() => {
      const SE: any = this.$refs.search
      SE.focus()
    })
  }

  /**
   *
   * @param force 强制刷新
   */
  private queryHandler(force: boolean = false) {
    const val = this.selectVal.trim()
    // 当前字数必须大于用户指定字数
    if (
      (!force &&
        this.defaultProps.minSearchSize > val.length &&
        val.length !== 0) ||
      !this.showPopover
    ) {
      return
    }

    this.showTree = false

    if (!(this.parentId || '').trim()) {
      this.$message.warning('请选择区域')

      return
    }

    this.$nextTick(() => {
      this.showTree = true
    })
  }

  private handleNodeClick(data: any) {
    if (data.selectable) {
      this.showPopover = false
      this.$emit('handleNodeClick', { ...data, isSelect: true })
    } else {
      this.$message.warning('当前节点不能选择')
    }
  }

  private currentChange() {
    // 选中节点变化时
  }

  private nodeExpand(data: any, node: any) {
    // 展开子节点
    //
  }

  private renderContent(
    h: any,
    { node, data, store }: { node: any; data: any; store: any }
  ) {
    return (
      <span class="custom-tree-node">
        <span
          {...{
            domProps: { innerHTML: this.keyRegExp(node.label, this.selectVal) },
          }}
        />
      </span>
    )
  }

  keyRegExp(val: string, keyword: string) {
    const keywords = keyword.trim()
    const vals = `${val}`
    if (val.indexOf(keyword) !== -1 && keywords !== '') {
      return vals.replace(keyword, `<font color="#0075E9">${keywords}</font>`)
    }

    return vals
  }

  private loadNode(node: any, resolve: any) {
    if (node.level === 0) {
      this.$emit('init', { resolve, text: this.selectVal, isFirst: true })
    } else if (node.data && node.data.subList && node.data.subList.length > 0) {
      resolve(node.data.subList)
    } else {
      this.$emit('init', {
        uuid: node.data.uuid,
        resolve,
        text: this.selectVal,
      })
    }
  }

  // private hide() {
  // 	this.showTree = false;
  // }

  private close() {
    this.showPopover = false
  }

  @Watch('value', { immediate: true })
  private valueChange(val: string) {
    this.currentValue = val.trim()
    this.showTree = false
  }

  @Watch('defaultProps', { immediate: true })
  private defaultPropsWatch(val: any) {
    this.treeProps = Object.assign(
      {
        children: 'subList',
        label: 'fullName',
        isLeaf: 'isLeaf',
      },
      val
    )
  }

  @Watch('parentId')
  private parentIdChange(val: any) {
    if (val) {
      // 所选区域变化之后要清除
      this.parentHasChange = true
      this.selectVal = ''
      this.showTree = false
    }
  }
}
